package com.example.seed.config.security;

import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(CustomLogoutSuccessHandler.class);

    @Resource
    private TokenService tokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //TODO 清除用户上下文
        log.info("清除用户上下文");
        SecurityContextHolder.clearContext();
        //TODO 清空用户token
        tokenService.logout(request);

        //TODO 记录登出日志
        log.info("记录登出日志");

        //TODO 返回登出成功
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");

        response.getWriter().write("{\"code\":\"200\",\"msg\":\"退出成功\"}");
        response.getWriter().flush();
        response.getWriter().close();

        //response.getWriter().write("登出成功");
    }
}
